/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wf.plccom;

import java.io.IOException;
import java.util.Date;
import wf.units.PLCComUnit;

/**
 *
 * @author student
 */
public class PLCLowLevel {
    private static final String GET_PATTERN = "/HOSTLINK/${COMMAND}";
    private String getEEPCommand;
    private String setEEPCommand;
    private String getCNTCommand;
    private String setCNTCommand;
    private String setDMCommand;
    private String getDMCommand;
    private String setSystemVariableCommand;
    private String getSystemVariableCommand;
    private String ip;

    public PLCLowLevel(String ip) {
        getEEPCommand = GET_PATTERN.replace("${COMMAND}", "RXI");
        setEEPCommand = GET_PATTERN.replace("${COMMAND}", "WXI");
        getCNTCommand = GET_PATTERN.replace("${COMMAND}", "RU");
        setCNTCommand = GET_PATTERN.replace("${COMMAND}", "WU");
        getDMCommand = GET_PATTERN.replace("${COMMAND}", "RVD");
        setDMCommand = GET_PATTERN.replace("${COMMAND}", "WVD");
        setSystemVariableCommand = GET_PATTERN.replace("${COMMAND}", "WVS");
        getSystemVariableCommand = GET_PATTERN.replace("${COMMAND}", "RVS");
        //HttpConnectionParams.setSoTimeout(httpc.getParams(), 1000);
        this.ip = ip;
    }

    public static String toHex(int address) {
        return Integer.toHexString(address).toUpperCase();
    }

    private String timestamp() {
        return "?%0C" + new Date().getTime();
    }

    private String send(String url) throws IOException {
        return PLCComUnit.UNIT.sendRequest(url + timestamp(), ip);
    }

    /**
     * read data from the memory of $count size from address $address
     * @param address
     * @param count
     * @return
     * @throws IOException
     */
    public Word[] getEEP(int address, int count) throws IOException {
        String ret = send(getEEPCommand + pad(toHex(address),4) + pad(Integer.toHexString(count), 2));
        System.err.println("GET EEP FROM "  + address + " RETURNED " + ret.trim());
        return createWordArray(ret.trim().substring(3).toCharArray());
    }

    public Word[] setEEP(int address, int count, String hexData) throws IOException {
        String ret = send(setEEPCommand + pad(toHex(address),4) + pad(Integer.toHexString(count),2) + hexData + "00*");
        System.err.println("SET EEP RETURNED " + ret.trim());
        return createWordArray(ret.trim().substring(3).toCharArray());
    }

    public Word[] getCNT(int count) throws IOException {
        String ret = send(getCNTCommand + pad(""+toHex(count-1),2));
        return createWordArray(ret.trim().substring(2).toCharArray());
    }

    public Word[] setCNT(int counter, int val) throws IOException {
        String ret = send(setCNTCommand + pad(""+toHex(counter-1),2) + pad(toHex(val),4));
        return createWordArray(ret.trim().substring(2).toCharArray());
    }

    public Word[] getDM(int count) throws IOException {
        String ret = send(getDMCommand + pad(""+count,4));
        System.err.println("GET DM RECIVED: " + ret.trim());
        return createWordArray(ret.trim().substring(3).toCharArray());
    }

    public Word[] setDM(int counter, int val) throws IOException {
        String ret = send(setDMCommand + pad(""+counter,4) + pad(toHex(val),4));
        return createWordArray(ret.trim().substring(3).toCharArray());
    }

    public Word[] setPLCSystemVariable(int type, int index, String hexData) throws IOException {
        String ret = send(setSystemVariableCommand + pad(toHex(type),2) + pad(Integer.toHexString(index),2) + pad(hexData,4));
        System.err.println("SET EEP RETURNED " + ret.trim());
        return createWordArray(ret.trim().substring(3).toCharArray());
    }
    
    public Word[] getPLCSystemVariable(int type, int index) throws IOException {
        String ret = send(getSystemVariableCommand + pad(toHex(type),2) + pad(Integer.toHexString(index),2));
        System.err.println("GET EEP RETURNED " + ret.trim());
        return createWordArray(ret.trim().substring(3).toCharArray());
    }
    
    public static String pad(String num, int size){
        while (num.length() < size){
            num = "0" + num;
        }

        return num;
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        int j = 0xc;
        System.out.println("i is "  + Integer.toHexString(j) );



        if (1==1) return;


        PLCLowLevel c = new PLCLowLevel("192.168.0.30");
        //while (true){
        //  Thread.sleep(1000);
        printWords(c.getEEP(0x008D, 32));
        System.out.println("Current Call: ");
        System.out.println("Counter is: ");
        printWords(c.getCNT(1));
        //System.out.println(c.getCNT("01"));
        //}
    }

    private static void printWords(Word[] value) {
        for (Word b : value) {
            System.out.println("" + b.toString());
        }
    }

    private Word[] createWordArray(char[] chars) {
        Word[] words = new Word[chars.length / 4];
        int pos = 0;
        for (int i=0; i<chars.length; i+=4){
            words[pos++] = new Word(chars[i], chars[i+1], chars[i+2], chars[i+3]);
        }

        return words;
    }

    String getIP() {
        return this.ip;
    }
}
